package com.fary.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.fary.constant.TemplateMessageConstant;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class WeChatWxMpService {

    @Autowired
    private WxMpService wxMpService;

    public boolean sendTemplateMsg(Map<String, String> keywordMap) {
        String result = "";
        if (MapUtil.isNotEmpty(keywordMap)) {
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            List<WxMpTemplateData> data = new ArrayList<>();
            wxMpTemplateMessage.setData(data);
            keywordMap.forEach((key, value) -> {
                if (StrUtil.equals(key, TemplateMessageConstant.TEMPLATE_ID)) {
                    wxMpTemplateMessage.setTemplateId(value);
                } else if (StrUtil.equals(key, TemplateMessageConstant.TO_USER)) {
                    wxMpTemplateMessage.setToUser(value);
                } else if (StrUtil.equals(key, TemplateMessageConstant.URL)) {
                    wxMpTemplateMessage.setUrl(value);
                } else {
                    data.add(new WxMpTemplateData(key, value));
                }
            });
            try {
                result = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                log.info("result:{}", result);
                return Boolean.TRUE;
            } catch (Exception e) {
                // 记录错误日志
                log.error("e:{}", e);
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }
}
